import 'dart:convert';
import 'package:injectable/injectable.dart';
import 'package:vista/shared/models/like_frame.dart';
import 'package:vista/shared/models/tutorial_video.dart';
import 'package:vista/shared/services/storage_service.dart';

/// 教程视频服务
/// 处理摄影教程视频的管理、点赞、查看，如摄影教学般组织视频内容
@lazySingleton
class TutorialVideoService {
  final StorageService _storageService;
  static const String _videosKey = 'tutorial_videos';
  static const String _likesPrefix = 'video_likes_';
  static const String _viewCountsPrefix = 'video_view_counts_';
  static const String _isInitializedKey = 'tutorial_videos_initialized';

  TutorialVideoService(this._storageService);

  /// 初始化默认教程视频数据
  /// 创建3条默认视频数据
  Future<void> initializeDefaultVideos() async {
    final isInitialized = await _storageService.retrieveBool(_isInitializedKey);
    if (isInitialized == true) {
      return; // 已经初始化过了
    }

    final now = DateTime.now();
    final defaultVideos = <TutorialVideo>[];

    // 创建3条默认视频
    final videoTitles = [
      'Mastering Composition: Rule of Thirds',
      'Understanding Light: Golden Hour Photography',
      'Camera Settings: Aperture and Depth of Field',
    ];

    final coverImages = [
      'assets/images/tutorial_cover_1.png',
      'assets/images/tutorial_cover_2.png',
      'assets/images/tutorial_cover_3.png',
    ];

    final defaultViewCounts = [1250, 980, 1560];

    for (int i = 0; i < videoTitles.length; i++) {
      final videoId = 'video_${now.millisecondsSinceEpoch}_$i';
      defaultVideos.add(
        TutorialVideo(
          id: videoId,
          title: videoTitles[i],
          videoPath: 'assets/videos/tutorial_${i + 1}.mp4',
          coverImage: coverImages[i],
          viewCount: defaultViewCounts[i],
          createdAt: now.subtract(Duration(days: 10 - i * 3)),
        ),
      );
    }

    // 保存所有数据
    await _saveVideos(defaultVideos);
    await _storageService.persistBool(_isInitializedKey, true);
  }

  /// 保存视频列表
  Future<void> _saveVideos(List<TutorialVideo> videos) async {
    final videosJson = videos.map((v) => v.toJson()).toList();
    final videosString = jsonEncode(videosJson);
    await _storageService.persistString(_videosKey, videosString);
  }

  /// 获取所有视频
  Future<List<TutorialVideo>> getAllVideos() async {
    final videosString = await _storageService.retrieveString(_videosKey);
    if (videosString == null) {
      return [];
    }

    try {
      final List<dynamic> videosJson = jsonDecode(videosString);
      return videosJson
          .map((json) => TutorialVideo.fromJson(json as Map<String, dynamic>))
          .toList()
        ..sort((a, b) => b.createdAt.compareTo(a.createdAt));
    } catch (e) {
      return [];
    }
  }

  /// 根据ID获取视频
  Future<TutorialVideo?> getVideoById(String videoId) async {
    final videos = await getAllVideos();
    try {
      return videos.firstWhere((v) => v.id == videoId);
    } catch (e) {
      return null;
    }
  }

  /// 增加视频查看次数
  Future<void> incrementViewCount(String videoId) async {
    final video = await getVideoById(videoId);
    if (video == null) {
      return;
    }

    final key = '$_viewCountsPrefix$videoId';
    final currentCount = await _storageService.retrieveInt(key);
    final newCount = (currentCount ?? video.viewCount) + 1;
    await _storageService.persistInt(key, newCount);

    // 更新视频列表中的查看次数
    final videos = await getAllVideos();
    final index = videos.indexWhere((v) => v.id == videoId);
    if (index != -1) {
      final updatedVideo = TutorialVideo(
        id: video.id,
        title: video.title,
        videoPath: video.videoPath,
        coverImage: video.coverImage,
        viewCount: newCount,
        createdAt: video.createdAt,
      );
      videos[index] = updatedVideo;
      await _saveVideos(videos);
    }
  }

  /// 获取视频的查看次数
  Future<int> getViewCount(String videoId) async {
    final key = '$_viewCountsPrefix$videoId';
    final storedCount = await _storageService.retrieveInt(key);
    if (storedCount != null) {
      return storedCount;
    }

    // 如果没有存储的查看次数，返回视频模型中的默认值
    final video = await getVideoById(videoId);
    return video?.viewCount ?? 0;
  }

  /// 获取视频的点赞列表
  Future<List<LikeFrame>> getLikes(String videoId) async {
    final key = '$_likesPrefix$videoId';
    final likesString = await _storageService.retrieveString(key);
    if (likesString == null) {
      return [];
    }

    try {
      final List<dynamic> likesJson = jsonDecode(likesString);
      return likesJson
          .map((json) => LikeFrame.fromJson(json as Map<String, dynamic>))
          .toList()
        ..sort((a, b) => b.timestamp.compareTo(a.timestamp));
    } catch (e) {
      return [];
    }
  }

  /// 获取视频的点赞数量
  Future<int> getLikeCount(String videoId) async {
    final likes = await getLikes(videoId);
    return likes.length;
  }

  /// 检查用户是否已点赞
  Future<bool> isLiked(String videoId, String userId) async {
    final likes = await getLikes(videoId);
    return likes.any((like) => like.userId == userId);
  }

  /// 点赞视频
  Future<void> likeVideo(String videoId, String userId) async {
    if (await isLiked(videoId, userId)) {
      return; // 已经点赞过了
    }

    final likes = await getLikes(videoId);
    likes.add(
      LikeFrame(
        id: 'like_${DateTime.now().millisecondsSinceEpoch}_$videoId',
        postId: videoId, // 复用LikeFrame，使用postId字段存储videoId
        userId: userId,
        timestamp: DateTime.now(),
      ),
    );

    final key = '$_likesPrefix$videoId';
    final likesJson = likes.map((like) => like.toJson()).toList();
    final likesString = jsonEncode(likesJson);
    await _storageService.persistString(key, likesString);
  }

  /// 取消点赞
  Future<void> unlikeVideo(String videoId, String userId) async {
    final likes = await getLikes(videoId);
    likes.removeWhere((like) => like.userId == userId);

    final key = '$_likesPrefix$videoId';
    if (likes.isEmpty) {
      await _storageService.removeKey(key);
    } else {
      final likesJson = likes.map((like) => like.toJson()).toList();
      final likesString = jsonEncode(likesJson);
      await _storageService.persistString(key, likesString);
    }
  }

  /// 删除视频
  Future<void> deleteVideo(String videoId) async {
    final videos = await getAllVideos();
    videos.removeWhere((video) => video.id == videoId);
    await _saveVideos(videos);

    // 同时删除相关的点赞和查看次数
    final likesKey = '$_likesPrefix$videoId';
    await _storageService.removeKey(likesKey);

    final viewCountsKey = '$_viewCountsPrefix$videoId';
    await _storageService.removeKey(viewCountsKey);
  }
}
